package com.dldata.devtools30.controller.metadata;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.entity.DevtModelMetadataFieldEntity;
import com.dldata.devtools30.service.metadata.DevtModelMetadataFieldService;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/DevtModelMetadataFieldController")
public class DevtModelMetadataFieldController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    DevtModelMetadataFieldService metadataFieldService;

    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAll(@RequestParam Map<String, String> paramMap){
        String tableid =paramMap.get("tableid");

        List<DevtModelMetadataFieldEntity> metadataTableEntities = metadataFieldService.getAllByTid(tableid);

        return Result.ok(metadataTableEntities);
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(DevtModelMetadataFieldEntity entity){
        if(StringUtil.isEmptyOrLength0(entity.getFieldName())){
            return Result.error("字段名不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getFieldCode())){
            return Result.error("字段代码不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getFieldType())){
            return Result.error("字段类型不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getFormId())){
            return Result.error("字段所属表不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getId())){
            entity.setId(UUID.randomUUID().toString());
        }

        List<DevtModelMetadataFieldEntity> fieldEntities=  metadataFieldService.getAllByTid(entity.getFormId());
        for (int i = 0; i < fieldEntities.size(); i++) {
            DevtModelMetadataFieldEntity metadataFieldEntity = fieldEntities.get(i);
            if(metadataFieldEntity.getFieldCode().equalsIgnoreCase(entity.getFieldCode())&&!metadataFieldEntity.getId().equalsIgnoreCase(entity.getId())){
                return Result.error("字段代码重复！");
            }
            if(metadataFieldEntity.getXh().equals(entity.getXh()) && !metadataFieldEntity.getId().equalsIgnoreCase(entity.getId())){
                return Result.error("字段序号重复！");
            }
        }
        entity.setFieldCode(entity.getFieldCode().toUpperCase());

         metadataFieldService.save(entity);

        return Result.ok();
    }
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam Map<String, String> paramMap){

        String id =paramMap.get("id");
        if(StringUtil.isEmptyOrLength0(id)){
            return  Result.error("参数有误");
        }
        try {
            metadataFieldService.deleteOne(id);
        }
        catch (Exception ex){

            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return  Result.error("操作错误，请稍候再试!");
        }
        return  Result.ok("删除成功");
    }
    @RequestMapping(value = "saveAll")
    @ResponseBody
    public Result saveAll(String fromId, HttpServletRequest request, HttpServletResponse response) throws  Exception{
        if(StringUtil.isEmptyOrLength0(fromId)){
            return  Result.error("参数有误");
        }
        try {
            List<DevtModelMetadataFieldEntity> sysCrfFormFieldEntitiesDb= metadataFieldService.getAllByTid(fromId);

            BufferedReader reader=new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
            StringBuilder jsonStringBuilder= new StringBuilder();
            String tmpStr=null;
            while ((tmpStr=reader.readLine())!=null){
                jsonStringBuilder.append(tmpStr);
            }

            List<DevtModelMetadataFieldEntity> sysCrfFormFieldEntitiesJson=JSON.parseArray(jsonStringBuilder.toString(), DevtModelMetadataFieldEntity.class);
            for (Iterator<DevtModelMetadataFieldEntity> iterator = sysCrfFormFieldEntitiesJson.iterator(); iterator.hasNext(); ) {
                DevtModelMetadataFieldEntity sysCrfFormFieldEntity = iterator.next();

                if(sysCrfFormFieldEntity.getFieldCode().equalsIgnoreCase("ID")||sysCrfFormFieldEntity.getFieldCode().equalsIgnoreCase("MID")){
                    iterator.remove();
                    continue;
                }

                List<DevtModelMetadataFieldEntity> sysCrfFormFieldEntityDb=sysCrfFormFieldEntitiesDb.stream().filter(
                        sysCrfFormFieldEntity1 -> {
                            return sysCrfFormFieldEntity1.getFieldName().equalsIgnoreCase(sysCrfFormFieldEntity.getFieldName());
                        }
                ).collect(Collectors.toList());
                if(sysCrfFormFieldEntityDb!=null&&sysCrfFormFieldEntityDb.size()>0){
                    iterator.remove();
                    continue;
                }
//                if(sysCrfFormFieldEntityDb!=null&&sysCrfFormFieldEntityDb.size()>0){
//                    sysCrfFormFieldEntity.setId(sysCrfFormFieldEntityDb.get(0).getId());
//                }
                if (StringUtil.isEmptyOrLength0(sysCrfFormFieldEntity.getId())) {
                    sysCrfFormFieldEntity.setId(UUID.randomUUID().toString());
                }
                sysCrfFormFieldEntity.setFieldName(sysCrfFormFieldEntity.getFieldName());
                sysCrfFormFieldEntity.setFieldCode(sysCrfFormFieldEntity.getFieldCode().toUpperCase());
                sysCrfFormFieldEntity.setPkey(sysCrfFormFieldEntity.getPkey()==null?0:sysCrfFormFieldEntity.getPkey());

                sysCrfFormFieldEntity.setFormId(fromId);

            }
            for (int i = 0; i < sysCrfFormFieldEntitiesJson.size(); i++) {
                DevtModelMetadataFieldEntity sysCrfFormFieldEntity = sysCrfFormFieldEntitiesJson.get(i);
                metadataFieldService.save(sysCrfFormFieldEntity);
            }

            return Result.ok();

        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage(),ex);
            return Result.error("操作错误，请稍候再试！");
        }

    }
}
